# 解决 pyexecjs 编码报错 在import execjs之前加入以下代码
import json
import subprocess
import time
from functools import partial
subprocess.Popen = partial(subprocess.Popen, encoding='utf-8')
# 解决 pyexecjs 编码报错
import execjs
from hyper import HTTPConnection

class JavaScriptExecutor:
    def __init__(self, js_file_path):
        """
        初始化类，读取 JavaScript 文件并编译。
        :param js_file_path: JavaScript 文件的路径
        """
        try:
            with open(js_file_path, 'r', encoding='utf-8') as file:
                self.js_code = file.read()
            self.ctx = execjs.compile(self.js_code)
        except FileNotFoundError:
            print(f"错误：未找到文件 {js_file_path}。")
        except Exception as e:
            print(f"读取或编译文件时出错：{e}")

    def get_params_url(self, url, cookie):
        """
        调用 JavaScript 中的 getParamsUrl 函数。
        :param url: 要传入 getParamsUrl 函数的 URL 参数
        :param cookie: 要传入 getParamsUrl 函数的 Cookie 参数
        :return: getParamsUrl 函数的执行结果
        """
        try:
            return self.ctx.call("getParamsUrl", url, cookie)
        except Exception as e:
            print(f"调用 getParamsUrl 函数时出错：{e}")
            return None

    def de_data(self, encrypted_data):
        """
        调用 JavaScript 中的 deData 函数。
        :param encrypted_data: 要传入 deData 函数的加密数据
        :return: deData 函数的执行结果
        """
        try:
            return self.ctx.call("deData", encrypted_data)
        except Exception as e:
            print(f"调用 deData 函数时出错：{e}")
            return None

    def get_set_allowance(self, m, c):
        params_result = self.get_params_url(f'/v1/fee/planbal/{m}', c)
        if params_result is not None:
            # 发请求
            cur_t = int(time.time() * 1000)
            url = f'https://shop.10086.cn{params_result}?_={cur_t}'
            print(url)
            headers = {
                ":authority": "shop.10086.cn",
                ":method": "GET",
                ":path": f'{params_result}?_={cur_t}',
                ":scheme": "https",
                "accept": "application/json, text/javascript, */*; q=0.01",
                "accept-encoding": "gzip, deflate, br, zstd",
                "accept-language": "zh-CN,zh;q=0.9",
                "cache-control": "no-store, must-revalidate",
                "content-type": "*",
                "cookie": cookie,
                "expires": "0",
                "if-modified-since": "0",
                "pragma": "no-cache",
                "priority": "u=1, i",
                "referer": "https://shop.10086.cn/i/?f=packremainqry&welcome=1742355808261",
                "sec-ch-ua": "\"Google Chrome\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"",
                "sec-ch-ua-mobile": "?0",
                "sec-ch-ua-platform": "\"Windows\"",
                "sec-fetch-dest": "empty",
                "sec-fetch-mode": "cors",
                "sec-fetch-site": "same-origin",
                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
                "x-requested-with": "XMLHttpRequest"
            }

            conn = HTTPConnection('shop.10086.cn', port=443, secure=True)
            conn.request('GET', url=f'{params_result}?_={cur_t}', headers=headers)
            data = json.loads(conn.get_response().read().decode('utf-8'))
            print('原始结果：：', data)
            if data['retCode'] == '000000':
                out_param = data['data']['outParam']
                de_result = self.de_data(out_param)
                print('解析结果：：', de_result)
            elif data['retCode'] == '500003':
                print('cookie过期！')
            else:
                print('系统异常：', data['retMsg'])

if __name__ == "__main__":
    cookie = 'ssologinprovince=531; inx=myorders; inx2=returnorderqry; arialoadData=true; ariawapChangeViewPort=false; shopuid=c34d0924-492b-4d9d-8c4a-07000548132f; PHPSESSID=rjfuo3isp09k9nkk0lh0dcpapg; cart_code_key=rjfuo3isp09k9nkk0lh0dcpapg; CmLocation=531|535; CmProvid=sd; mobile=; vtime=1742355452018; WT_FPC=id=228bacd839bd6f436431742288141120:lv=1742355462895:ss=1742355451971; is_login=true; jsessionid-cmcc=nE725678546F8347702F281A40621C7B4-1; sendflag=20250319133741773358; lgToken=mhrz80ac12af4d29a3cac998edf80580; cvToken=mhrz114bd8d94dd196789029d8550d0f; CaptchaCode=HCRKtu; rdmdmd5=20971088F6D8C5B598137F61DD08E166; cmccssotoken=mhrz3315ec9b4b819a63cf56376844f8@.10086.cn; chargeresource=s%3D~e%3D~c%3D~taskId%3D'
    mobile = '手机号'
    executor = JavaScriptExecutor('yd_net.js')
    executor.get_set_allowance(mobile, cookie)
